package com.milo.easypoi.controller.export;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.milo.easypoi.entity.StudentEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

/**
 * 对象导出
 *
 * @author milogenius
 * @date 2020-10-12 17:31
 */
@Controller
@RequestMapping
@Slf4j
public class ObjectExcelExport {

    @RequestMapping("object")
    @ResponseBody
    public void download(ModelMap map) {
        log.info("Start==============");
        List<StudentEntity> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            StudentEntity stu = new StudentEntity();
            stu.setId(i + "");
            stu.setName(i + "name");
            if (i % 2 == 0) {
                stu.setSex(1);
            } else {
                stu.setSex(2);
            }
            stu.setBirthday(new Date(1));
            stu.setRegistrationDate(new Date(1));
            list.add(stu);
        }
        ExportParams params = new ExportParams("导出对象属性", "测试", ExcelType.XSSF);
        params.setFreezeCol(2);
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put(NormalExcelConstants.CLASS, StudentEntity.class);
        map.put(NormalExcelConstants.PARAMS, params);

        //表格标题属性导出
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("导出对象属性", "测试"), StudentEntity.class,
                list);
        try {
            //路径修改为自己本地路径
            FileOutputStream fos = new FileOutputStream("E:/excel/object.xlsx");
            workbook.write(fos);
            fos.close();
            log.info("End==========导出成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
